<template>
  <div class="order-list-container">
    <div class="header">
      <h1>我的订单</h1>
      <el-select v-model="statusFilter" placeholder="全部状态" @change="fetchOrders">
        <el-option label="全部状态" value="" />
        <el-option label="待支付" value="pending" />
        <el-option label="已支付" value="paid" />
        <el-option label="已发货" value="shipped" />
        <el-option label="已完成" value="delivered" />
        <el-option label="已取消" value="cancelled" />
      </el-select>
    </div>
    
    <div class="order-list" v-if="orders.length > 0">
      <div class="order-item" v-for="order in orders" :key="order.id">
        <div class="order-header">
          <div class="order-info">
            <span class="order-number">订单编号：{{ order.orderNumber }}</span>
            <span class="order-date">下单时间：{{ formatDate(order.createdAt) }}</span>
          </div>
          <div class="order-status">
            <el-tag :type="getStatusType(order.status)">{{ getStatusText(order.status) }}</el-tag>
          </div>
        </div>
        
        <div class="order-items">
          <div class="order-item-product" v-for="item in order.items" :key="item.id">
            <img :src="item.productImage" :alt="item.productName" class="product-image" />
            <div class="product-info">
              <div class="product-name">{{ item.productName }}</div>
              <div class="product-price">¥{{ item.unitPrice.toFixed(2) }}</div>
              <div class="product-quantity">x{{ item.quantity }}</div>
            </div>
          </div>
        </div>
        
        <div class="order-footer">
          <div class="order-total">
            共{{ order.items.length }}件商品 合计：<span class="total-amount">¥{{ order.totalAmount.toFixed(2) }}</span>
          </div>
          <div class="order-actions">
            <el-button type="text" @click="viewOrderDetail(order.id)">查看详情</el-button>
            <el-button v-if="order.status === 'pending'" type="primary" @click="payOrder(order.id)">立即支付</el-button>
            <el-button v-if="order.status === 'pending'" type="default" @click="cancelOrder(order.id)">取消订单</el-button>
          </div>
        </div>
      </div>
    </div>
    
    <div v-else class="empty-order">
      <el-empty description="暂无订单记录" />
    </div>
    
    <div class="pagination" v-if="total > 0">
    <el-pagination
    v-model:current-page="currentPage"
    v-model:page-size="pageSize"
    :page-sizes="[5, 10, 20]"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    @size-change="handleSizeChange"
     @current-change="handleCurrentChange"
    />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { orderService } from '../../api/orderService';
import type { Order } from '../../api/orderService';

const router = useRouter();
const orders = ref<Order[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const statusFilter = ref('');
const loading = ref(false);

// 获取订单列表
const fetchOrders = async () => {
  loading.value = true;
  try {
    const response = await orderService.getUserOrders({
      page: currentPage.value,
      limit: pageSize.value,
      status: statusFilter.value
    });
    
    // 确保正确处理响应数据结构
    if (response && response.data) {
      orders.value = response.data.orders || [];
      total.value = response.data.pagination?.total || 0;
    } else {
      orders.value = [];
      total.value = 0;
    }
  } catch (error) {
    ElMessage.error('获取订单列表失败');
    console.error('获取订单列表失败:', error);
    orders.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 查看订单详情
const viewOrderDetail = (orderId: number) => {
  router.push(`/order/${orderId}`);
};

// 支付订单
const payOrder = async (orderId: number) => {
  try {
    await orderService.processPayment(orderId);
    ElMessage.success('支付成功');
    fetchOrders(); // 重新获取订单列表
  } catch (error) {
    ElMessage.error('支付失败');
    console.error('支付失败:', error);
  }
};

// 取消订单
const cancelOrder = async (orderId: number) => {
  try {
    await orderService.cancelOrder(orderId);
    ElMessage.success('订单已取消');
    fetchOrders(); // 重新获取订单列表
  } catch (error) {
    ElMessage.error('取消订单失败');
    console.error('取消订单失败:', error);
  }
};

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).format(date);
};

// 获取订单状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: '待支付',
    paid: '已支付',
    shipped: '已发货',
    delivered: '已完成',
    cancelled: '已取消'
  };
  return statusMap[status] || status;
};

// 获取订单状态标签类型
const getStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    pending: 'primary',
    paid: 'success',
    shipped: 'info',
    delivered: 'success',
    cancelled: 'danger'
  };
  return typeMap[status] || 'default';
};

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  fetchOrders();
};

const handleCurrentChange = (current: number) => {
  currentPage.value = current;
  fetchOrders();
};

// 组件挂载时获取订单列表
onMounted(() => {
  fetchOrders();
});
</script>

<style scoped>
.order-list-container {
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h1 {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.order-list {
  margin-bottom: 20px;
}

.order-item {
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  margin-bottom: 20px;
  overflow: hidden;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #fafafa;
  border-bottom: 1px solid #e6e6e6;
}

.order-info {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #666;
}

.order-items {
  padding: 15px 20px;
}

.order-item-product {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.order-item-product:last-child {
  border-bottom: none;
}

.product-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  margin-right: 15px;
  border-radius: 4px;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 10px;
}

.product-price {
  font-size: 14px;
  color: #ff6700;
  margin-bottom: 5px;
}

.product-quantity {
  font-size: 14px;
  color: #666;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #fafafa;
  border-top: 1px solid #e6e6e6;
}

.order-total {
  font-size: 14px;
  color: #666;
}

.total-amount {
  font-size: 16px;
  color: #ff6700;
  font-weight: bold;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.empty-order {
  padding: 60px 0;
  text-align: center;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .order-list-container {
    padding: 10px;
  }
  
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .order-info {
    flex-direction: column;
    gap: 5px;
  }
  
  .order-item-product {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .product-image {
    width: 100%;
    height: auto;
    max-height: 200px;
  }
  
  .order-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .order-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .pagination {
    justify-content: center;
  }
}
</style>